<template>
	<view class="base-cloud">
		<view class="father" id="canvas">
			<view :class="{op0 : !ready}">
				<slot></slot>
			</view>
			<canvas :style="{width: width + 'rpx', height: height + 'rpx'}" class="abs pa" :disable-scroll="true" @touchstart="touchstart"
			@touchend="touchend" @touchmove="touchmove" canvas-id="scratch-card"></canvas>
		</view>
		
	</view>

</template>

<script>
	let ctx = null ;
    
	export default {
		name:"scratch-card",
		props: {
			percentage: {	//刮开百分之多少时候开奖
				type: Number,
				default: 40,
			},
			touchSize: {	//触摸画笔大小
				type: Number,
				default: 20
			},
			
			fillColor: {	//未刮开图层时得填充色
				type: String,
				default: '#999'
			},
			
			watermark: {	//水印文字
				type: String,
				default: '刮一刮'
			},
			
			watermarkColor: {	//水印文字颜色
				type: String,
				default: '#c5c5c5'
			},
			
			watermarkSize: {	//水印文字大小
				type: Number,
				default: 14
			},
			
			title: {	//提示文字
				type: String,
				default: '刮一刮开奖'
			},
			
			titleColor: {	//提示文字颜色
				type: String,
				default : '#888'
			},
			
			titleSize : { //提示文字大小
				type : Number ,
				default : 24 
			},
			
			disabled : { //是否禁止刮卡
				type : Boolean ,
				default : false 
			},
		},
		
		data() {
			return {
				width: 576,
				height: 288,
				startY: null,
				startX: null,
				computing: false,
				complete:false,
				reset: false,
				ready: false,
				storePoints: [],
                sum: 0,
				draw: {}
			};
		},
        onReady() {

        },
		onLoad() {
            
		},
		mounted() {
            ctx = uni.createCanvasContext("scratch-card", this)
            this.getRect()
		},
		
		methods: {
			getRect(e) {
				const query = uni.createSelectorQuery().in(this)
				query.select('#canvas').boundingClientRect(data => {
					setTimeout(e => {
						this.init()
					},20)
				}).exec()
			},
			
			init(e) {
				this.computing = false
				this.complete = false
				this.reset = false
				this.ready = false
                // 设置画笔宽度
				ctx.clearRect(0,0, this.width, this.height)
				//绘制画布
				ctx.setFillStyle(this.fillColor)
                // ctx.fillStyle="transparent";
				ctx.fillRect(0,0, this.width,this.height)
				this.ready = true
				//绘制文字水印
				this.fillWatermark();
				//绘制标题
				// this.fillTitle()
				ctx.draw()
			},
			
			/**
			 * 绘制文字水印
			 */
			fillWatermark(e) {
				if(!this.watermark) {
					return
				}
				
				let width = this.watermark.length * this.watermarkSize;
				
				ctx.save()
				ctx.rotate(-10 * Math.PI /180)
				
				let x = 0
				let y = 0
				let i = 0
				
				while((x <= this.width * 5 || y <= this.height * 5) && i<300) {
					
					ctx.setFillStyle(this.watermarkColor)
					ctx.setFontSize(this.watermarkSize)
					ctx.fillText(this.watermark, x, y)
					
					x += width + width * 1.6
					
					if (x > this.width && y <= this.height) {
						x = -Math.random() *100
						y += this.watermarkSize * 3
					}
					i ++
				}
				ctx.restore()
			},
			
			/**
			 * 绘制标题
			 */
			fillTitle(e) {
				if(!this.title) {
					return
				}
				ctx.setTextAlign("center")
				ctx.setTextBaseline("middle")
				ctx.setFillStyle(this.titleColor)
				ctx.setFontSize(this.titleSize)
				ctx.fillText(this.title, this.width / 2, this.height / 2);
			},
			luckdraw() {
                // 请求后端获取参数信息
                let obj = {
                    key: 'ggl'
                }
     //            this.$store.dispatch('activity/luckdraw', obj).then(res => {
					// // // console.log('抽奖成功',res)
     //                if (res.status != 1) return;
     //                this.$store.dispatch('init/get_Points');
                    this.sum++
     //            })
				this.$api('game.luckdraw',obj).then(res=> {
					// // // console.log(res,'res')
					this.draw = res
					this.$emit('getLuckdraw',res)
				})
            },
			touchstart(e) {
				if (this.disabled) {
					return
				}
				this.startX = e.touches[0].x;
				this.startY = e.touches[0].y;
                // 触碰canvas 开始请求后端
				// // // console.log(e,'e','sum',this.sum)
                if (this.sum < 1) {
                    this.luckdraw();
					// // // console.log('执行抽奖')
                }
			},
			
			touchend(e) {
				this.getFilledPercentage()
			},
			
			touchmove(e) {
				if (this.complete || this.disabled) {
					return
				}
				ctx.moveTo(this.startX, this.startY);
				ctx.clearRect(this.startX, this.startY, this.touchSize, this.touchSize);
				ctx.draw(true)
				//记录移动点位
				this.startX = e.touches[0].x
				this.startY = e.touches[0].y
			},
			getFilledPercentage(e) {
				if (this.computing) {
					return
				}
				
				this.computing = true;
				uni.canvasGetImageData({
					canvasId: 'scratch-card',
					x: 0,
					y: 0,
					width: this.width,
					height: this.height,
					success: (res) => {
						let pixels = res.data;
						let transPixels = []
						for (let i =0; i < pixels.length; i += 4) {
							if(pixels[i + 3] < 128) {
								transPixels.push(pixels[i + 3])
							}
						}
						let percent = (transPixels.length / (pixels.length / 2) * 100).toFixed(2)
						if (percent >= this.percentage) {
							this.success();
                           // // // console.log('success',this.sum)
						}
						this.computing = false
					},
					
					fail: (err) => {
						// // console.log(err);
					},
					
				}, this)
			},
			
			success(e) {
				this.complete = true
				if (this.reset) {
					return
				}
				this.reset = true
                this.init();
                this.sum = 0;
				this.$emit("luckDraw",this.draw)
			},
		}
		
		
	}
</script>

<style lang="scss" scoped>
	page{
		font: 14px/1.5 "Helvetica Neue", Helvetica, Arial, "Microsoft Yahei", "Hiragino Sans GB", "Heiti SC", "WenQuanYi Micro Hei", sans-serif;
		background-color: #f1f1f1;
	}
	
	body, html{
		box-sizing: border-box;
		user-select:auto!important;
	}
	/* 定位布局 */
	.father{
		position: relative;
	}
	
	.abs{
		left: 106rpx;
		right: 0;
		bottom: 176rpx;
		z-index: 1;
        background: #ffe4d3;
		&image{
			width: 100%;
			height: 100%;
		}
		&.top{
			bottom: auto;
		}
		&.bottom{
			top: auto;
		}
		&.left{
			right: auto;
		}
		&.right{
			left: auto;
		}
	}

</style>
